package com.platform.event.core.scheduler;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.w3c.dom.events.EventException;

import com.platform.event.core.EventService;
import com.platform.event.core.contants.EventConstants;
import com.platform.event.core.model.BaseEvent;
import com.platform.task.core.DistributeTask;
import com.platform.task.core.impl.ThreadPoolTaskSchedulerComponent;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHander;
@JobHander(value="historyEventHandler")
@Service
public class SerchAndHandleHistoryEvent extends IJobHandler implements DistributeTask {

	Logger logger = LoggerFactory.getLogger(SerchAndHandleHistoryEvent.class);

	@Resource
	protected ThreadPoolTaskSchedulerComponent threadPoolTaskSchedulerComponent;

	@Resource
	private EventService eventService;

	@Override
	public String getTaskName() {
		return SerchAndHandleHistoryEvent.class.getSimpleName();
	}

	@Override
	public void run() {
		List<BaseEvent> events = eventService.searchWaitDeleteEvent();
		final CountDownLatch latch = new CountDownLatch(events.size());
		for (final BaseEvent event : events) {
			threadPoolTaskSchedulerComponent.getThreadPool(EventConstants.DEFAULT_TASK, 20).execute(new Runnable() {
				@Override
				public void run() {
					try {
						eventService.handleDeleteEventProcess(event);
					} catch (EventException e) {
						logger.error(e.getMessage());
					} catch (Exception e) {
						logger.error(String.format("处理事件的时候发生异常, EventProcess[id=%d]", event.getId()), e);
					} finally {
						latch.countDown();
					}
				}

			});
		}
		try {
			// 等待事件异步处理完成
			latch.await(0, TimeUnit.SECONDS);
		} catch (InterruptedException e) {
			logger.error("", e);
		}
	}

	@Override
	public ReturnT<String> execute(String... params) throws Exception {
		// TODO Auto-generated method stub
		return null;
	}

}
